<?php  defined('BASEPATH') OR exit('No direct script access allowed');

class Tours extends Admin_Controller {

	private $_validation_rules = array(
		array(
				'field'	=> 'is_hotsale',
				'label'	=> 'lang:tours.is_hotsale',
				'rules'	=> 'required|numeric'
		),
		array(
				'field'	=> 'priceof1r1p',
				'label'	=> 'lang:tours.priceof1r1p',
				'rules'	=> 'numeric|max_length[5]'
		),
		array(
				'field'	=> 'priceof1r2p',
				'label'	=> 'lang:tours.priceof1r2p',
				'rules'	=> 'numeric|max_length[5]'
		),
		array(
				'field'	=> 'priceof1r3p',
				'label'	=> 'lang:tours.priceof1r3p',
				'rules'	=> 'numeric|max_length[5]'
		),
		array(
				'field'	=> 'priceof1r4p',
				'label'	=> 'lang:tours.priceof1r4p',
				'rules'	=> 'numeric|max_length[5]'
		),
		array(
				'field'	=> 'getin_type',
				'label'	=> 'lang:tours.getin_type',
				'rules'	=> 'required'
		),
		array(
				'field'	=> 'days',
				'label'	=> 'lang:tours.days',
				'rules'	=> 'required|numeric|max_length[2]'
		),
		array(
				'field'	=> 'departure_day',
				'label'	=> 'lang:tours.departure_day',
				'rules'	=> 'required'
		),
		array(
				'field'	=> 'departuredate_to',
				'label'	=> 'lang:tours.departuredate_to',
				'rules'	=> 'required'
		),
		array(
				'field'	=> 'departuredate_from',
				'label'	=> 'lang:tours.departuredate_from',
				'rules'	=> 'required'
		),
		array(
				'field'	=> 'serial',
				'label'	=> 'lang:tours.serial',
				'rules'	=> 'required|callback__check_serial_exist'
		),
		array(
				'field'	=> 'uri_segment',
				'label'	=> 'lang:tours.uri_segment',
				'rules'	=> 'required|callback__check_urisegment_exist'
		),
		array(
				'field'	=> 'type',
				'label'	=> 'lang:tours.type',
				'rules'	=> 'required'
		),
		array(
				'field'	=> 'available',
				'label'	=> 'lang:tours.available',
				'rules'	=> 'is_natural'
		),
		array(
				'field'	=> 'order_rating',
				'label'	=> 'lang:tours.order_rating',
				'rules'	=> 'numeric|max_length[3]'
		),
		array(
				'field'	=> 'tour_rating',
				'label'	=> 'lang:tours.tour_rating',
				'rules'	=> 'numeric|max_length[3]'
		),
			
		array(
				'field'	=> 'credits',
				'label'	=> 'lang:tours.credits',
				'rules'	=> 'optional|integer|max_length[5]'
		),
		array(
				'field'	=> 'price',
				'label'	=> 'lang:tours.price',
				'rules'	=> 'required|integer|max_length[5]'
		),
		array(
				'field'	=> 'discountprice',
				'label'	=> 'lang:tours.discountprice',
				'rules'	=> 'optional|integer|max_length[5]'
		),
		array(
				'field'	=> 'channel_id',
				'label'	=> 'lang:tours.channel_id',
				'rules'	=> 'required|is_natural_no_zero'
		),
		array(
				'field'	=> 'image',
				'label'	=> 'lang:tours.image',
				'rules'	=> 'optional|numeric'
		),
		array(
				'field'	=> 'sort',
				'label'	=> 'lang:tours.sort',
				'rules'	=> 'numeric'
		)
	);
	public function __construct()
	{
		parent::__construct();
		$this->lang->load('tours/tours');
		$this->load->model('tours/tours_model', 'tours_m');
		
		$this->load->library('form_validation');
		$supported_languages = $this->config->item('supported_languages');
		
		foreach($supported_languages as $language => $lang_content){
			if(CURRENT_LANGUAGE == $language){
				$rules = 'required';
			}else{
				$rules = 'optional';
			}
			$this->_validation_rules[] = array(
					'field'	=> 'name_'. $language,
					'label'	=> 'lang:tours.name_label',
					'rules'	=> $rules. '|max_length[80]'
			);
			
			$this->_validation_rules[] = array(
					'field'	=> 'highlights_'. $language,
					'label'	=> 'lang:tours.highlights',
					'rules'	=> 'max_length[255]'
			);
			$this->_validation_rules[] = array(
					'field'	=> 'considerations_'. $language,
					'label'	=> 'lang:tours.considerations',
					'rules'	=> 'max_length[255]'
			);
			$this->_validation_rules[] = array(
					'field'	=> 'price_inclusions_'. $language,
					'label'	=> 'lang:tours.price_inclusions',
					'rules'	=> 'max_length[255]'
			);
			$this->_validation_rules[] = array(
					'field'	=> 'price_exclusions_'. $language,
					'label'	=> 'lang:tours.price_exclusions',
					'rules'	=> 'max_length[255]'
			);
		}
		$this->form_validation->set_rules($this->_validation_rules);
		
		$this->load->model('regions/regions_model', 'regions_m');
		array_unshift($this->shortcuts, array('name' => lang('menu_2_catalog_tours'), 'link' => site_url('admin/catalog/tours')),
				array('name' => lang('menu_2_catalog_create_tour'), 'link' => site_url('admin/catalog/create_tour')));
		$this->load->model('channels/channels_model', 'channels_m');
		$this->template->set_data(array(
				'channels' => $this->channels_m->get_lang_list(array('visible' => 1), CURRENT_LANGUAGE),
				'shortcuts' => $this->shortcuts
		));
	}

	// ------------------------------------------------------------------------

	public function index()
	{
		$pagination = create_pagination('admin/catalog/tours' , $this->tours_m->count_lang_list(FALSE, CURRENT_LANGUAGE), 15, 4);
		$tours = $this->tours_m->get_lang_list(array('offset' =>$pagination['limit'][1], 'limit' => $pagination['limit'][0], 'order_by' => 'created DESC'), CURRENT_LANGUAGE);
		$this->template->load('tours/list', array(
			'pagination' => $pagination,
			'tours' => $tours
		));
	}

	// ------------------------------------------------------------------------

	/**
	 * Checks if the element save process can be done.
	 *
	 * @returns		Boolean		True if the save can be done, false if not
	 *
	 */
	function _check_before_save()
	{
		$default_lang = Settings_lib::get('site_lang');
		$default_lang_name = $this->input->post('name_'.$default_lang);
	
		if ($default_lang_name == FALSE)
		{
			return FALSE;
		}
	
		return TRUE;
	}
	
	// ------------------------------------------------------------------------
	
	public function create()
	{
		
		if ($this->form_validation->run())
		{
			if ($this->_check_before_save() == TRUE)
			{
				list($data, $lang_data) = $this->_prepare_data($this->tours_m->get_table());
				$data['created'] = $data['updated'] = time();
				$data['departure_day'] = implode(",", $data['departure_day']);
				$data['departuredate_from'] = strtotime($data['departuredate_from']);
				$data['departuredate_from'] = strtotime($data['departuredate_to']);
				$tour_id = $this->tours_m->save($data, $lang_data);
				
				if($tour_id){
					$message	= lang('tours.create_success');
					$status		= 'success';
				}else{
					$message	= lang('tours.create_error');
					$status		= 'error';
				}
				$this->session->set_flashdata($status, $message);
				redirect('admin/catalog/tours');
			}
		}

		foreach ($this->_validation_rules as $rules)
		{
			$tour->{$rules['field']} = set_value($rules['field']);
		}
		$tour->departure_day = empty($tour->departure_day)?array(): $this->input->post('departure_day');
		$this->data['tour'] = $tour;
		$this->template->set('site_title', lang('tours.create_title'))->load('tours/create', $this->data);
	}

	// ------------------------------------------------------------------------
	
	
	public function search()
	{
		$available = $this->input->post('available');
		$channel = $this->input->post('channel');
		$keyword = $this->input->post('keyword');
		$type = $this->input->post('type');
	
		$url_available = substr($this->uri->segment(4, 'available_'), 10);
		$url_channel = substr($this->uri->segment(5, 'channel_'), 8);
		$url_keyword = url_base64_decode(substr($this->uri->segment(6, 'keyword_'), 8));
	
		$keyword = $keyword === FALSE? $url_keyword: $keyword;
		$available = $available === FALSE? $url_available: $available;
		$channel = $channel === FALSE? $url_channel: $channel;
	
		$where = array();
		if('all' != $available){
			$where['available'] = $available;
		}
		if(!empty($channel)){
			$where['channel_id'] = $channel;
		}
		if(FALSE != $keyword && "" != trim($keyword)){
			if('name_type' == $type){
				$where['like'] = array('name' => trim($keyword));
			}else{
				$where['like'] = array('serial' => trim($keyword));
			}
		}
	
		$pagination = create_pagination(
				'admin/catalog/search_tours/type_'. $type. '/available_' . $available. '/channel_'. $channel . '/keyword_'. url_base64_encode($keyword) , $this->tours_m->count_lang_list($where, CURRENT_LANGUAGE), 15, 8);
		$tours = $this->tours_m->get_lang_list($where + array('offset' =>$pagination['limit'][1], 'limit' => $pagination['limit'][0]), CURRENT_LANGUAGE);
		$this->template->load('tours/search', array(
				'tours' => $tours,
				'keyword' => $keyword,
				'channel' => $channel,
				'type' => $type,
				'pagination' => $pagination,
				'available' => $available
		));
	}
	
	// ------------------------------------------------------------------------

	public function edit($id = 0)
	{
		$tour = $this->tours_m->get($id);
		if ( ! $tour)
		{
			redirect('admin/catalog/tours');
		}
		$tour_lang = $this->tours_m->get_lang(array('id' => $id));
		$tour->langs = fetch_lang($tour_lang);
		
		$this->_validation_rules[] = array(
				'field'	=> 'serial',
				'label'	=> 'lang:tours.serial',
				'rules'	=> 'required|callback__check_edit_serial_exist'
		);
		$this->_validation_rules[] = array(
				'field'	=> 'uri_segment',
				'label'	=> 'lang:tours.uri_segment',
				'rules'	=> 'required|callback__check_edit_urisegment_exist'
		);
		$this->form_validation->set_rules($this->_validation_rules);
		
		if ($this->form_validation->run())
		{
			if ($this->_check_before_save() == TRUE)
			{
				list($data, $lang_data) = $this->_prepare_data($this->tours_m->get_table());
				$data['updated'] = time();
				$data['departure_day'] = implode(",", $data['departure_day']);
				$departuredate_from = explode('/', $data['departuredate_from']);
				$departuredate_to = explode('/', $data['departuredate_to']);
				
				$data['departuredate_from'] = mktime(0, 0, 0, intval($departuredate_from[1]), intval($departuredate_from[0]), intval($departuredate_from[2]));
				$data['departuredate_to'] = mktime(0, 0, 0, intval($departuredate_to[1]), intval($departuredate_to[0]), intval($departuredate_to[2]));
				$tour_id = $this->tours_m->save($data, $lang_data);
	
				if($tour_id){
					$message	= lang('tours.create_success');
					$status		= 'success';
				}else{
					$message	= lang('tours.create_error');
					$status		= 'error';
				}
			}
			$this->session->set_flashdata($status, $message);
			redirect('admin/catalog/tours');
		}
		$this->load->model('regions/regions_model', 'regions_m');
		$this->data['cities'] = $this->regions_m->get_lang_list(array('region_type' => 3), CURRENT_LANGUAGE);
		$tour->departure_day = explode(",", $tour->departure_day);
		$this->data['tour'] = $tour;

		$this->template->set('site_title', sprintf(lang('tours.edit_title'), def_lang($tour, 'name')))->load('tours/edit', $this->data);
	}

	// ------------------------------------------------------------------------

	public function delete($id = 0)
	{
		$ids = $id
			? is_array($id)
				? $id
				: array($id)
			: (array) $this->input->post('action_to');

		$total		= sizeof($ids);
		$deleted	= array();
		
		$this->load->model('dailyplans/dailyplans_model', 'dailyplans_m');
		$this->load->model('dailyplans/dailyattractions_model', 'dailyattractions_m');
		$this->load->model('dailyplans/dailypickuppoints_model', 'dailypickuppoints_m');
		$this->load->model('dailyplans/dailyroute_model', 'dailyroute_m');
		
		// Try do deletion
		foreach ($ids as $id)
		{
			// Get the row to use a value.. as title, name
			if ($tour = $this->tours_m->_get($id, CURRENT_LANGUAGE))
			{
				// Make deletion retrieving an status and store an value to display in the messages
				$deleted[($this->tours_m->delete($id) ? 'success': 'error')][] = $tour->name;
				$dailyplans = $this->dailyplans_m->get_many_by('tour_id', $id);
				foreach($dailyplans as $dailyplan){
					$this->dailypickuppoints_m->delete_by('daily_plan_id', $dailyplan->id);
					$this->dailypickuppoints_m->delete_by('daily_plan_id', $dailyplan->id);
					$this->dailyroute_m->delete_by('daily_plan_id', $dailyplan->id);
				}
				$this->dailyplans_m->delete_by('tour_id', $id);
			}
		}

		// Set status messages
		foreach ($deleted as $status => &$values)
		{
			// Mass deletion
			if (($status_total = sizeof($values)) > 1)
			{
				$last_value		= array_pop($values);
				$first_values	= implode(', ', $values);

				// Success / Error message
				$values = sprintf(lang('tours.delete_mass_' . $status), $status_total, $total, $first_values, $last_value);
			}

			// Single deletion
			else
			{
				// Success / Error messages
				$values = sprintf(lang('tours.delete_' . $status), $values[0]);
			}
		}

		// He arrived here but it was not done nothing, certainly valid ids not were selected
		if ( ! $deleted)
		{
			$status		= 'error';
			$deleted	= array('error' => lang('tours.no_select_error'));
		}
		else
		{
			$status = array_key_exists('error', $deleted) ? 'error': 'success';
		}

		foreach ($deleted as $status => $message)
		{
			$this->session->set_flashdata($status, $message);
		}

		redirect('admin/catalog/tours');
	}

	// ------------------------------------------------------------------------

	public function action()
	{
		$action = strtolower($this->input->post('btnAction'));
		
		if ($action)
		{
			// Get the id('s)
			$id_array = $this->input->post('action_to');

			// Call the action we want to do
			if (method_exists($this, $action))
			{
				return $this->{$action}($id_array);
			}
		}

		redirect('admin/catalog/tours');
	}
	
	public function _check_serial_exist($serial){
		if(count($this->tours_m->get_by('serial', $serial)) > 0){
			$this->form_validation->set_message('_check_serial_exist', sprintf(lang('tours.duplicate_error'), $serial));
			return FALSE;
		}else{
			return TRUE;
		}
	}
	public function _check_edit_serial_exist($serial){
		if ( count($this->tours_m->get_by(array('serial' => $serial, 'id <>' => $this->input->post('id')))) > 0){
			$this->form_validation->set_message('_check_edit_serial_exist', sprintf(lang('tours.duplicate_error'), $serial));
			return FALSE;
		}else{
			return TRUE;
		}
	}
	public function _check_urisegment_exist($uri_segment){
		if(count($this->tours_m->get_by('uri_segment', $uri_segment)) > 0){
			$this->form_validation->set_message('_check_urisegment_exist', sprintf(lang('tours.urisegment_duplicate_error'), $uri_segment));
			return FALSE;
		}else{
			return TRUE;
		}
	}
	public function _check_edit_urisegment_exist($uri_segment){
		if ( count($this->tours_m->get_by(array('uri_segment' => $uri_segment, 'id <>' => $this->input->post('id')))) > 0){
			$this->form_validation->set_message('_check_edit_urisegment_exist', sprintf(lang('tours.urisegment_duplicate_error'), $uri_segment));
			return FALSE;
		}else{
			return TRUE;
		}
	}
}
